package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.Md5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.system.mapper.RoleMapper;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 业务实现类：员工
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void add(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        Logininfo logininfo = employee2logininfo(employee);
        logininfoMapper.add(logininfo);//生成自增长id

        employee.setLogininfoId(logininfo.getId());
        super.add(employee);

        //保存中间表的信息
        employeeMapper.saveEmployeeRole(employee);
    }

    private Logininfo employee2logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        logininfo.setDisable(true);
        return logininfo;
    }

    @Override
    public void delete(Long id) {
        //取出来存储在内存出，不在数据库
        Employee employee = employeeMapper.findById(id);
        //删除emp
        super.delete(id);
        //删除role
        employeeMapper.removeEmployeeRoleByEmployeeId(id);
        //删除logininfo
        logininfoMapper.delete(employee.getLogininfoId());
    }

    @Override
    public void update(Employee employee) {
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        //修改logininfo
        Employee employee1 = employeeMapper.findById(employee.getId());
        Long id = employee1.getLogininfoId();
        Logininfo logininfo = employee2logininfo(employee);
        logininfo.setId(id);
        logininfoMapper.update(logininfo);

        super.update(employee);

        //删除中间表信息
        employeeMapper.removeEmployeeRoleByEmployeeId(employee.getId());
        //保存新的信息
        employeeMapper.saveEmployeeRole(employee);
    }


    @Override
    public List<Employee> list(Long id) {
        return employeeMapper.list(id);
    }
}
